<?php

require_once 'init.php';
require_once 'shop_common.php';

$group = new Group($par->get('catId'));
$smarty->assign('group',$group);

$descendants = new DescendantGroups($group->id());
$smarty->assign('descendants',$descendants->toArray());

$IDs = $descendants->IDs();
$IDs[] = $group->id();

$manufacturerId = null;
if ($par->exist('manufacturer'))
{
	$manufacturerId = $par->asStr('manufacturer');
	if (strlen($manufacturerId))
	{
		$manufacturerId = Manufacturer::toID($manufacturerId);
	}
	else
	{
		$manufacturerId = null;
	}
}

$showAll = ($par->exist('show') && $par->get('show')=='all') ? true : false;

if ($group->hasProducts() || $showAll)
{
	$sql = "
		SELECT cf_products_in_groups.product_id 
		FROM cf_products_in_groups
		INNER JOIN cf_product_attributes ON cf_product_attributes.product_id=cf_products_in_groups.product_id
		INNER JOIN cf_products ON cf_product_attributes.product_id=cf_products.id
		WHERE group_id IN (" . ($showAll ? implode(',',$IDs) : $group->id()) . ")
		  AND cf_product_attributes.attribute_id=".Attribute::toID('wholesale_price')."
		  ". ($manufacturerId ? "AND cf_products.manufacturer_id=$manufacturerId" : "") . "
		ORDER BY sort_order ASC
	";
	
	$smarty->assign('recCount', DB::countRecords($sql));
	
	$skip = $par->exist('skip') ? $par->get('skip') : 0;
	$smarty->assign('recSkip', $skip);

	$q = createQuery(limitSelect($sql, SHOW_PRODUCTS_ON_PAGE, $skip));
	$q->execute();
	
	$products = array();
	$manufacturers = array();
	$productImages = array();
	
	while ($q->fetch()) 
	{
		$productId = $q->at(0);
		$product = new Product($productId);
		$products[] = $product;

		$manufacturer = new Manufacturer($product->manufacturerId());
		$manufacturers[] = $manufacturer;
		
		if (count($product->images())) 
		{
			$images = $product->images();
			$productImages[] = $images[0];
		}
		else {
			$productImages[] = null;
		}
	}
	
	$smarty->assign('products',$products);
	$smarty->assign('manufacturers',$manufacturers);
	$smarty->assign('productImages',$productImages);
}

$allManufacturers = array();
$q = createQuery("
	SELECT DISTINCT cf_products.manufacturer_id
	FROM cf_products
	INNER JOIN cf_products_in_groups ON cf_products.id=cf_products_in_groups.product_id
	INNER JOIN cf_product_attributes ON cf_product_attributes.product_id=cf_products.id
	WHERE cf_products_in_groups.group_id IN (".implode(',',$IDs).")
	  AND cf_product_attributes.attribute_id=".Attribute::toID('wholesale_price')."
");
$q->execute();
while ($q->fetch()) 
{
	$allManufacturers[] = new Manufacturer($q->at(0));
}
$smarty->assign('allManufacturers',$allManufacturers);


show(
	'category',
	$group->name(),
	groupToCrumbs($group)
);

?>